import { ChangeEvent, FC, ReactNode } from 'react';

import { Input } from 'antd';

import { debounce } from 'lodash';
import Category, { IconItem } from './Category';
import { useState } from 'react';

import './style/index.less';

const { Search } = Input;

export interface Categories {
  [key: string]: {
    category: ReactNode;
    icons: IconItem[];
  };
}

export interface IconViewProps {
  categories: Categories;
}

const IconView: FC<IconViewProps> = ({ categories }) => {
  const [searchKey, setSearchKey] = useState<string | undefined>(undefined);

  const handleSearchIcon = (e: ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;

    setSearchKey(value ? value.toLowerCase() : undefined);
  };

  const renderCategories = () => {

    return Object.keys(categories)
      .map((key) => {
        const { icons } = categories[key];
        return {
          ...categories[key],
          key,
          icons: searchKey
            ? icons?.filter(({ name, value }) => {
                return (
                  name.toLowerCase().includes(searchKey) || value.toLowerCase().includes(searchKey)
                );
              })
            : icons,
        };
      })
      .filter(({ icons }) => !!icons?.length)
      .map(({ category, icons, key }) => <Category key={key} title={category} icons={icons} />);
  };
  return (
    <>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Search
          placeholder="在此搜索图标,点击图标可复制代码"
          style={{ margin: '0 10px', flex: 1 }}
          allowClear
          onChange={debounce(handleSearchIcon, 300)}
          size="large"
          autoFocus
        />
      </div>
      {renderCategories()}
    </>
  );
};

export default IconView;
